package entity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;
import util.Validator;

public class MonthlyReceipt {
	public String id;
	public String carId;
	public String parkId;
	public Integer month;
	public String startDate;
	public String endDate;
	public String money;
	public String createTime;
		
	public List<String[]> query(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select id,carId,parkId,month,startDate,endDate,money,createTime from pm_monthly_receipt where true";
		if(Validator.isNotEmpty(params[0])){
			sql += " and carId like concat('%',?,'%')";
			list.add(params[0]);
		}
		sql += " order by id desc";
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 8);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}
	
	public boolean save() {
		String sql = "insert into pm_monthly_receipt(carId,parkId,month,startDate,endDate,money,createTime) values "
				+ "(?,?,?,?,?,?,?)";
		Object[] paraArray = {carId,parkId,month,startDate,endDate,money,createTime};
		try {
			int count = DBUtil.update(sql, paraArray);
			return count > 0;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public List<String[]> summarize(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select date_format(a.createTime,'%Y-%m-%d'),b.TYPE,ROUND(sum(replace(a.money,'元','') + 0),2)"
				+ " from pm_monthly_receipt a JOIN pm_park b ON a.parkId = b.id where TRUE ";		
		if(Validator.isNotEmpty(params[0])){
			sql += " and date_format(a.createTime,'%Y-%m-%d') >= ?";
			list.add(params[0]);
		}
		if(Validator.isNotEmpty(params[1])){
			sql += " and date_format(a.createTime,'%Y-%m-%d') <= ?";
			list.add(params[1]);
		}
		sql += " GROUP BY date_format(a.createTime,'%Y-%m-%d'),b.TYPE ORDER BY date_format(a.createTime,'%Y-%m-%d'),b.TYPE";
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 3);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}

}
